<script setup lang="ts">
  import { useGetOptions } from '@/services/pages/return-factory/useModule'
  import _ from 'lodash'
  import { useGetFaultOptions } from '@/services/pages/know/useFault'
  import { computed, onMounted, ref } from 'vue'
  import {
    FormInstance,
    UploadFile,
    UploadRawFile,
    ElForm,
    ElFormItem,
    ElSelect,
    ElOption,
    ElInput,
    ElDatePicker,
    ElUpload,
    ElIcon,
  } from 'element-plus'
  import { UploadFilled } from '@element-plus/icons-vue'
  import { HMessageBox } from '@/components/common/message'
  import infoTip from '@/config/info-tip'
  import moment from 'moment'
  import { useGetModuleDetail } from '@/services/pages/return-factory/useModule'
  import { useGetNetworkOptions } from '@/services/pages/network/useNetwork'

  const {
    options: moduleOptions,
    getOptionsLoading: getModuleOptionsLoading,
    getOptionsParam: getModuleOptionsParam,
    getOptions: getModuleOptions,
  } = useGetOptions()
  const {
    options: faultOptions,
    loading: getFaultOptionsLoading,
    getOptionsParam: getFaultOptionsParam,
    getOptions: getFaultOptions,
  } = useGetFaultOptions()
  const { moduleDetail, getModuleDetail } = useGetModuleDetail()
  const {
    loading: getOptionsLoading,
    options: networkOptions,
    getOptionsParam: getNetworkOptionsParam,
    getOptions: getNetworkOptions,
  } = useGetNetworkOptions()

  defineOptions({
    name: 'BasicInfoReturnFactoryCreate',
  })

  type Form = Pick<
    ReturnFactoryAPIRequest.Create,
    'createTime' | 'faultDescr' | 'source' | 'repairModuleId' | 'repairDescr' | 'networkId'
  > & { fileList: Array<UploadRawFile> }

  const emits = defineEmits<{
    (e: 'change-module', value: string): void
  }>()

  // 表单
  const form = ref<Form>({
    source: 1,
    repairModuleId: '',
    faultDescr: '',
    repairDescr: '',
    createTime: '',
    fileList: [],
    networkId: '',
  })

  // 文件列表
  const fileList = ref<Array<{ file: UploadRawFile; url: string }>>([])

  // 附件预览链接列表
  const filePreviewUrls = computed(() => {
    const result: Array<string> = []

    fileList.value.forEach((file) => {
      if (file.file.type.includes('image')) {
        result.push(file.url)
      }
    })

    return result
  })

  // 表单校验规则
  const rules = ref({
    source: [{ required: true, message: '请选择返厂来源', trigger: ['change', 'blur'] }],
    repairModuleId: [{ required: true, message: '请选择返厂品类', trigger: ['change', 'blur'] }],
    createTime: [{ required: true, message: '请选择报单时间', trigger: ['change', 'blur'] }],
    networkId: [{ required: false, message: '请选择网点', trigger: ['change', 'blur'] }],
  })

  // 表单组件实例
  const formInstance = ref<FormInstance | null>(null)

  /**
   * 文件选择
   * @param {UploadFile} uploadFile - 文件对象
   */
  const handleUploadFile = (uploadFile: UploadFile) => {
    if (uploadFile.raw) {
      if (!uploadFile.raw.type.includes('image')) {
        HMessageBox.error(infoTip.returnFactory.create.file_type_fail)
        return
      }

      if (fileList.value.length >= 10) {
        HMessageBox.error(infoTip.returnFactory.create.file_count_fail)
        return
      }

      if (uploadFile.raw.size / 1024 / 1024 > 50) {
        HMessageBox.error(infoTip.returnFactory.create.file_size_fail)
        return
      }

      fileList.value.push({
        file: uploadFile.raw,
        url: URL.createObjectURL(uploadFile.raw),
      })
    }
  }

  /**
   * 删除文件
   * @param {Number} uid - uid
   */
  const handleDelFile = (uid: number) => {
    fileList.value = fileList.value.filter((file) => file.file.uid !== uid)
  }

  /**
   * 获取模块下拉选项
   */
  const handleGetModuleOptions = _.debounce((keyword: string) => {
    if (getModuleOptionsParam.value.name !== keyword) {
      getModuleOptionsParam.value.name = keyword
      getModuleOptions()
    }
  }, 600)

  /**
   * 获取故障类型下拉选项
   */
  const handleGetFaultOptions = _.debounce((keyword: string) => {
    if (getFaultOptionsParam.value.name !== keyword) {
      getFaultOptionsParam.value.name = keyword
      getFaultOptions()
    }
  }, 600)

  /**
   * 更新返厂品类事件
   */
  const handleChangeModule = async () => {
    await getModuleDetail(form.value.repairModuleId)
    rules.value['networkId'][0].required = false
    if (moduleDetail.value.enabledNetwork) {
      getNetworkOptions()
      rules.value['networkId'][0].required = true
    }
    emits('change-module', form.value.repairModuleId)
  }

  /**
   * 报单时间选择事件
   */
  const handleChangeCreateTime = () => {
    form.value.createTime = moment(form.value.createTime).format('YYYY-MM-DD HH:mm')
  }

  /**
   * 获取网点下拉选项
   */
  const handleGetNetworkOptions = _.debounce((keyword: string) => {
    if (getNetworkOptionsParam.value.name !== keyword) {
      getNetworkOptionsParam.value.name = keyword
      getNetworkOptions()
    }
  }, 600)

  onMounted(() => {
    form.value.createTime = moment().format('YYYY-MM-DD HH:mm')
  })

  defineExpose({
    getModuleOptions,
    getFaultOptions,
    getForm: async () => {
      if (formInstance.value) {
        try {
          await formInstance.value.validate()
          form.value.fileList = fileList.value.map((file) => file.file)
          return form.value
        } catch (error) {
          return null
        }
      }
      return null
    },
    setForm: (param: typeof form.value) => {
      form.value = param
    },
  })
</script>

<template>
  <div class="return-factory-info">
    <div class="title">返厂信息</div>
    <div class="form">
      <el-form
        ref="formInstance"
        inline-message
        label-width="85"
        :rules="rules"
        :model="form"
        label-position="top"
      >
        <!-- 返厂来源 -->
        <el-form-item label="返厂来源" prop="source">
          <el-select v-model="form.source" placeholder="请选择返厂来源" disabled>
            <el-option :value="1" label="系统创建"></el-option>
          </el-select>
        </el-form-item>

        <!-- 返厂品类 -->
        <el-form-item label="返厂品类" prop="repairModuleId">
          <el-select
            v-model="form.repairModuleId"
            placeholder="请选择返厂品类"
            :loading="getModuleOptionsLoading"
            filterable
            :filter-method="handleGetModuleOptions"
            @change="handleChangeModule"
          >
            <el-option
              v-for="(option, optionIndex) in moduleOptions"
              :key="optionIndex"
              :label="option.name"
              :value="option.id"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item>

        <!-- 故障类型 -->
        <!-- <el-form-item label="故障类型" prop="faultDescr">
          <el-select
            v-model="form.faultDescr"
            placeholder="请选择故障类型"
            :loading="getFaultOptionsLoading"
            filterable
            :filter-method="handleGetFaultOptions"
          >
            <el-option
              v-for="(option, index) in faultOptions"
              :key="index"
              :label="option.name"
              :value="option.name"
              :disabled="option.disabled"
            />
          </el-select>
        </el-form-item> -->

        <!-- 服务网点 -->
        <el-form-item
          v-if="moduleDetail && moduleDetail.enabledNetwork"
          label="服务网点"
          prop="networkId"
        >
          <el-select
            v-model="form.networkId"
            :loading="getOptionsLoading"
            :filter-method="handleGetNetworkOptions"
            clearable
            filterable
            placeholder="请选择网点"
            remote-show-suffix
          >
            <el-option
              v-for="item in networkOptions"
              :key="item.name"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>

        <!-- 返厂产品问题 -->
        <el-form-item label="返厂产品问题">
          <el-input
            v-model.trim="form.repairDescr"
            type="textarea"
            placeholder="请输入返厂产品问题"
            maxlength="200"
            show-word-limit
            resize="both"
          />
        </el-form-item>

        <!-- 报单时间 -->
        <el-form-item label="报单时间" class="create-time" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            type="datetime"
            placeholder="请选择报单时间"
            format="YYYY-MM-DD HH:mm"
            date-format="MMM DD, YYYY"
            time-format="HH:mm"
            @change="handleChangeCreateTime"
          />
        </el-form-item>

        <!-- 上传图片 -->
        <el-form-item label="上传图片（最多只能上传10张）" class="file-upload">
          <el-upload
            :auto-upload="false"
            :show-file-list="false"
            accept="image/*"
            action="#"
            drag
            multiple
            :on-change="handleUploadFile"
          >
            <el-icon :size="24" color="#007cff">
              <UploadFilled />
            </el-icon>
          </el-upload>
          <div v-for="(file, index) in fileList" :key="index" class="file">
            <h-image
              :width="80"
              :height="50"
              :padding="2"
              :initial-index="index"
              :preview-src-list="filePreviewUrls"
              :src="file.url"
              @del="handleDelFile(file.file.uid)"
            ></h-image>

            <h-tooltip-text :text="file.file.name" :max-width="80" :height="16"></h-tooltip-text>
          </div>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
  .return-factory-info {
    display: flex;
    flex-direction: column;

    .title {
      padding-left: 6px;
      border-left: 3px solid $primaryColor;
      font-size: 14px;
      font-weight: bold;
    }

    .form {
      :deep(.el-form) {
        display: grid;
        grid-template-columns: repeat(auto-fill, 440px);
        column-gap: 100px;
        margin-top: 18px;
        row-gap: 18px;
        padding: 0 38px;

        .file-upload {
          .el-form-item__content {
            display: flex;
            flex-direction: row;
            gap: 5px;
          }
        }

        .create-time {
          .el-form-item__content {
            .el-date-editor {
              width: 100%;
            }
          }
        }

        .el-form-item {
          .el-form-item__label {
            height: 16px;
            line-height: 16px;
            margin: 0 0 3px 0;
          }

          .el-form-item__content {
            width: 100%;
            align-items: flex-start;

            .el-form-item__error {
              padding: 0;
              margin: 3px 0 0 0;
            }

            .el-textarea {
              width: 100%;

              .el-textarea__inner {
                width: 100% !important;
                min-height: 28px !important;
                height: 28px;
                max-height: 150px !important;
              }
            }

            .el-upload {
              width: 80px;
              height: 50px;

              .el-upload-dragger {
                padding: 0;
                width: 100%;
                height: 100%;
                display: flex;
                flex-direction: column;
                justify-content: center;
                align-items: center;

                .iconfont,
                .text {
                  color: #606266;
                }

                .iconfont {
                  font-size: 24px;
                  width: 24px;
                  line-height: 24px;
                  height: 24px;
                }

                .text {
                  height: 16px;
                  line-height: 16px;
                }
              }
            }

            .file-list {
              display: flex;
              flex-wrap: wrap;
              gap: 5px;
              margin-top: 5px;

              .file {
                width: 69px;
                display: flex;
                flex-direction: column;
              }
            }
          }
        }
      }
    }
  }
</style>
